//
//  APIToday.m
//  Bracelet
//
//  Created by jing zhao on 2/15/15.
//  Copyright (c) 2015 jing zhao. All rights reserved.
//

#import "APITodayTotal.h"
#import "FileReadAndWrite.h"

#define FILENAMECACHE_APIWORKOUTTODAYTOTAL @"fileName_apiWorkoutTodayTotal"

@implementation APITodayTotal

-(instancetype) initFromTodayData:(NSDictionary*)dic
{
    self = [super init];
    if (self) {
        self.strLast_update_time = [dic objectForKey:APIKEYLAST_UPDATE_TIME];
        self.strNextChallenge = [dic objectForKey:APIKEYNEXTCHALLENGE];
        self.strPercent = [dic objectForKey:APIKEYPERCENT];
        self.strRunTotal_metre = [dic objectForKey:APIKEYRUNTOTAL_METRE];
        self.strTotalDays = [dic objectForKey:APIKEYTOTALDAYS];
        self.strTotalMoney = [dic objectForKey:APIKEYTOTAL_MONEY];
        self.strHtml = [dic objectForKey:APIKEYHTML];
    }
    return self;
}


+(instancetype)apiTodayWithData:(NSDictionary*)dic
{
    return [[self alloc]initFromTodayData:dic];
}



+(void)setApiRelativePosition:(NSString*)relativePostion
           getTheTodayMyToTal:(void (^)(APITodayTotal *todayAndWeek)) successBlock
                      failure:(void (^)( NSError *error)) failureBlock
{
    NSString *strUserId = [[NSUserDefaults standardUserDefaults]objectForKey:USERID];
    NSDictionary *headerData =@{@"BasicAuthUsername":strUserId};
    NSDictionary *data = @{@"flag":@"all",@"ios_android_flag":@"ios"};

  [[APIConnection shareInstance]post:relativePostion data:data header:headerData netError:^(NSError *error) {
      failureBlock(error);
      
      //取缓存
      NSDictionary *dicCanch = [FileReadAndWrite getTheStorageDataWithFile:FILENAMECACHE_APIWORKOUTTODAYTOTAL];
      if (dicCanch) {
          NSDictionary *dicSuccess = [dicCanch objectForKey:APIKEYData];
          successBlock([APITodayTotal apiTodayWithData:dicSuccess]);
      }
      
  } apiFinish:^(id data) {
      
      NSDictionary *dictionaryTemp = data;
      NSInteger codeTemp= [[dictionaryTemp objectForKey:APIKEYCODE]integerValue];
      if (codeTemp ==0) {
          NSDictionary *dicSuccess = [data objectForKey:APIKEYData];
          successBlock([APITodayTotal apiTodayWithData:dicSuccess]);
          
          //存入缓存
          [FileReadAndWrite storageDataWithFile:FILENAMECACHE_APIWORKOUTTODAYTOTAL andData:dictionaryTemp];
      }
      else
      {
          failureBlock(nil);
      }
  }];
}


@end
